package com.ruoyi.common.utils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;

/**
 * @author : liangrc
 * @date : 2021/3/8 17:09
 * @Description : 切面去除查询返回字段值null
 */
@Configuration
public class JacksonConfig {

    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        System.err.println("JacksonConfig初始化成功！");
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        SerializerProvider serializerProvider = objectMapper.getSerializerProvider();
        serializerProvider.setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
                String fieldName = jsonGenerator.getOutputContext().getCurrentName();
                Class objType = jsonGenerator.getCurrentValue().getClass();
                try {
                    // 通过get方法判断字段类型
                    String fieldTypeName =
                            objType
                                    .getMethod("get" + ((char) (fieldName.charAt(0) - 32)) + fieldName.substring(1))
                                    .getReturnType()
                                    .getTypeName();
                    if (String.class.getTypeName().equals(fieldTypeName)) {
                        jsonGenerator.writeString("");
                    } else if (fieldTypeName.endsWith("[]")) {
                        jsonGenerator.writeStartArray();
                        jsonGenerator.writeEndArray();
                    } else {
                        jsonGenerator.writeNull();
                    }
                } catch (Exception e) {
                    jsonGenerator.writeNull();
                }
            }
        });
        return objectMapper;
    }
}
